import sys
import os

def Parse (srcFile, parametersFile, skipNum):        
    results = []
    open_prices = []
    close_prices = []
    high_prices = []
    low_prices = []
    ave_prices = []
    dates = []
    times = []
    
    print "Start reading files!"    
    with open(srcFile, 'r') as handle:
        for i in xrange(skipNum+1):
            priceStr = handle.readline()
        while len(priceStr)>0:
            priceStrList = priceStr.split(',')
            dates.append(priceStrList[0])
            times.append(priceStrList[1])
            close_prices.append(float(priceStrList[5]))
            open_prices.append(float(priceStrList[2]))
            high_prices.append(float(priceStrList[3]))
            low_prices.append(float(priceStrList[4]))
            ave_prices.append(GetAvePrice(priceStrList))
            priceStr = handle.readline()   
    print "Finished reading files!", os.linesep
    
    results.append(dates)
    results.append(times)
    results.append(close_prices)
    results.append(open_prices)
    results.append(high_prices)
    results.append(low_prices)
    results.append(ave_prices)

    # TODO: change the open_prices to the close_prices of the moving average and minmax
    print "Start calculating moving average!"
    movingIntervals = GetParameters(parametersFile, 'Moving Average')
    for interval in movingIntervals:
        results.append(GetMovingAverage(open_prices, interval))        
    print "Finished calculating moving average!", os.linesep
    
    print "Start calculating minmax!"
    minmaxIntervals = GetParameters(parametersFile, 'MinMax Interval')
    for interval in minmaxIntervals:
        minvalues, maxvalues = GetMinMax(open_prices, interval)
        results.append(minvalues)
        results.append(maxvalues)
    print "Finished calculating minmax!", os.linesep
    return results

def GetMovingAverage(data, interval):
    result = [];
    for index in xrange(len(data)):
        result.append(0)
    intergral = 0.0
    if (interval > len(data)):
        return result
    else:
        intergral = sum(data[0:interval])
        result[interval-1] = intergral/interval
        for i in xrange(interval-1):
            result[i] = result[interval-1]
    for index in xrange(interval, len(data)):
        intergral -= data[index-interval]
        intergral += data[index]
        result[index] = intergral/interval
    return result

def GetMinMax(data, interval):
    resultmin = [];
    resultmax = [];
    for index in xrange(len(data)):
        resultmin.append(0)
        resultmax.append(0)
    minvalue, maxvalue, minindex, maxindex = GetMinMaxAndIndex(data, 0, interval)
    if (interval > len(data)):
        return (resultmin, resultmax)
    else:
        resultmin[interval-1] = minvalue
        resultmax[interval-1] = maxvalue
        for i in xrange(interval-1):
            resultmin[i] = resultmin[interval-1]
            resultmax[i] = resultmax[interval-1]
    for index in xrange(interval, len(data)):
        if ((minindex <= (index-interval)) or (maxindex <= (index-interval))):
            minvalue, maxvalue, minindex, maxindex = GetMinMaxAndIndex(data, (index-interval+1), interval)
        else:
            if (data[index]<minvalue):
                minvalue = data[index]
                minindex = index
            if (data[index]>maxvalue):
                maxvalue = data[index]
                maxindex = index
        resultmin[index] = minvalue
        resultmax[index] = maxvalue
    return (resultmin, resultmax)

def GetMinMaxAndIndex(data, begin, number):
    minvalue = data[begin]
    maxvalue = data[begin]
    minindex = begin
    maxindex = begin
    for index in range(begin, begin+number):
        if (data[index]<minvalue):
            minvalue = data[index]
            minindex = index
        if (data[index]>maxvalue):
            maxvalue = data[index]
            maxindex = index
    return (minvalue, maxvalue, minindex, maxindex)

def GetAvePrice(strList):
    return 0.5*(float(strList[3]) + float(strList[4]))
    
def GetParameters(fileName, key):
    parameterFile = file(fileName, 'r')
    parameters = []
    for line in parameterFile:
        if len(line)>0:
            strList = line.split('=')
            if (len(strList)==2) and (strList[0].strip()==key):
                movingIntervalStr = strList[1]
                for intervalStr in movingIntervalStr.split():
                    parameters.append(int(intervalStr))
    parameterFile.close()
    return parameters
    
if __name__ == "__main__":
    if (len(sys.argv) == 4):
        from time import clock
        print os.linesep, "Start calculating!", os.linesep
        start = clock()
        results = Parse(sys.argv[1], sys.argv[2], int(sys.argv[3]))
        end = clock()
        print "Elapsed time: ", (end-start), " seconds."
        print "Finish calculating!", os.linesep
        
        print "Start outputting data!"
        start = clock()
        filePath = sys.argv[1]
        outBuf = file(os.path.join(os.path.dirname(filePath), '_SAMPLES.'.join(os.path.basename(filePath).rsplit('.', 1))), 'w')
        dataNum = len(results[0])
        for j in xrange(dataNum):
            for i in xrange(len(results)):
                outBuf.write(str(results[i][j]))
                outBuf.write('\t')
            outBuf.write('\n')
        outBuf.close()
        end = clock()
        print "Elapsed time: ", (end-start), " seconds."
        print "Finish outputting data!", os.linesep
    else:
        print "Parameters is not acceptable!"
        

